package io.sundial.util;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

/**
 * 网络工具类
 *
 * @author Payne 646742615@qq.com
 * 2018/12/13 13:30
 */
public class NetKit {

    /**
     * 获得外网IP，如果无法获得外网IP，则返回本地IP
     *
     * @return 外网IP/本地IP
     */
    public static String address() {
        try {
            String localhost = InetAddress.getLocalHost().getHostAddress();
            Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
            while (interfaces.hasMoreElements()) {
                Enumeration<InetAddress> addresses = interfaces.nextElement().getInetAddresses();
                while (addresses.hasMoreElements()) {
                    InetAddress address = addresses.nextElement();
                    if (address instanceof Inet4Address && address.isSiteLocalAddress() && !address.getHostAddress().equals(localhost)) {
                        return address.getHostAddress();
                    }
                }
            }
            return localhost;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
